package logic

import (
	"context"
	"golang.org/x/crypto/bcrypt"
	"google.golang.org/grpc/status"
	"zeroOne/models"

	"zeroOne/user_srv/user_rpc/internal/svc"
	"zeroOne/user_srv/user_rpc/user_pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *user_pb.UserRegRequest) (*user_pb.UserRegResponse, error) {
	// todo: add your logic here and delete this line
	username := in.Username
	password := in.Password

	var count int64
	err := l.svcCtx.DB.Model(&models.User{}).Where("username = ?", username).Count(&count).Error
	if err != nil {
		return nil, status.Error(50000, err.Error())
	}

	if count > 0 {
		return nil, status.Error(42201, "此用户已注册")
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return nil, status.Error(50000, err.Error())
	}

	newUser := &models.User{
		Username: username,
		Password: string(hashedPassword),
	}

	err = l.svcCtx.DB.Create(newUser).Error
	if err != nil {
		return nil, status.Error(50000, err.Error())
	}

	return &user_pb.UserRegResponse{
		Id: newUser.Id,
	}, nil
}
